package com.android.webttest.Config;

import android.content.Context;
import android.util.Log;

import com.android.webttest.Api.Service.AppApiService;
import com.android.webttest.Api.Service.CategoryApiService;
import com.android.webttest.Api.Service.CheckcodeApiService;
import com.android.webttest.Api.Service.GoodApiService;
import com.android.webttest.Api.Service.UserApiService;
import com.android.webttest.Intercepter.AuthInterceptor;
import com.android.webttest.utils.TokenManager;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    private static final String BASE_URL  = "http://10.0.2.2:8080/"; // 使用10.0.2.2
    private static Retrofit retrofit = null;

    private static String token = "";
    // 带 token 的 Retrofit 实例
    public static Retrofit getClientWithToken(Context context){
        try {
            token = TokenManager.readAndDecryptToken(context);
            if (token == null || token.isEmpty()) {
                Log.w("ApiClient", "Token is empty or null");
            } else {
                Log.d("ApiClient", "Loaded token: " + token);
            }
        } catch (Exception e) {
            Log.e("ApiClient", "Failed to load token", e); // 更细粒度记录错误
            return getClient(); // fallback to unauthenticated client for testing
        }

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new AuthInterceptor(token)); // 添加 AuthInterceptor 并传递 token

        // 设置 readTimeout 为 30 秒
        httpClient.readTimeout(30, TimeUnit.SECONDS);
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build();
    }

    // 无 token 的 Retrofit 实例
    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

    //生成接口
    public static CheckcodeApiService getCheckcodeClient() {
        return getClient().create(CheckcodeApiService.class);
    }

    public static UserApiService getUserApiServiceClient() {
        return getClient().create(UserApiService.class);
    }

    public static GoodApiService getGoodApiServiceClient(Context context) {
        return getClientWithToken(context).create(GoodApiService.class);
    }
    public static CategoryApiService getCategoryApiServiceClient(Context context) {
        return getClientWithToken(context).create(CategoryApiService.class);
    }
    public static AppApiService getAppApiServiceClient(Context context) {
        return getClientWithToken(context).create(AppApiService.class);
    }
}